import _ from "lodash";

const words = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

/**
 * 获取列
 * @param {*} end
 * @returns 从 A 开始到 end
 */
function getExcelColsIndex(end: any) {
	if (end.length === 1) {
		return words.slice(0, words.indexOf(end) + 1).split("");
	} else if (end.length === 2) {
		const arr = words.split("");
		const arr1 = words.slice(0, words.indexOf(end.charAt(1)) + 1).split("");
		const arr2 = arr1.map(i => {
			return "A" + i;
		});
		return arr.concat(arr2);
	} else {
		const arr = words.split("");
		const arr1 = arr.map(i => {
			return "A" + i;
		});
		const arr2 = words.slice(0, words.indexOf(end.charAt(2)) + 1).split("");
		const arr3 = arr2.map(i => {
			return "B" + i;
		});
		return arr.concat(arr1).concat(arr3);
	}
}

function getColIndex(word: any) {
	return words.indexOf(word);
}

/**
 * 工作簿转数组数据
 * @param {import('xlsx-js-style').WorkSheet} sheet 工作簿
 * @param {string} endCol 结束列号
 * @param {number} start 起始行数
 */
export function sheet2Data(sheet: any, endCol: any, start = 0) {
	const cols = getExcelColsIndex(endCol);
	const keyNumberRegExp = /[\w+](\d+)$/;
	const maxRow = _.reduce(
		_.keys(sheet),
		(max: any, key: any) => {
			let [, row] = keyNumberRegExp.exec(key) || [];

			if (row) {
				row = _.parseInt(row) + "";
				max = max < Number(row) ? Number(row) : max;
			}

			return max;
		},
		0
	);

	const tableData = [];
	for (let rowIndex = start; rowIndex <= maxRow; rowIndex++) {
		const tableItem: any = [];

		_.forEach(cols, colIndex => {
			const key = `${colIndex}${rowIndex}`;
			tableItem.push(_.get(sheet[key], "v", null));
		});

		tableData.push(tableItem);
	}

	return tableData;
}
